package com.platform.modules.app.controller;

import com.platform.common.annotation.SysLog;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.JwtUtils;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.modules.custmoer.dto.*;
import com.platform.modules.custmoer.entity.CustRecordEntity;
import com.platform.modules.custmoer.entity.CustomerEntity;
import com.platform.modules.custmoer.entity.StaffEntity;
import com.platform.modules.custmoer.entity.StaffMapEntity;
import com.platform.modules.custmoer.service.CustRecordService;
import com.platform.modules.custmoer.service.CustomerService;
import com.platform.modules.custmoer.service.StaffMapService;
import com.platform.modules.custmoer.service.StaffService;
import com.platform.modules.sys.entity.SysUserEntity;
import io.jsonwebtoken.Claims;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/app/staff")
public class AppStaffController {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private StaffService staffService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustRecordService custRecordService;
    @Autowired
    private StaffMapService staffMapService;


    /**
     * 获取我的客户
     * @param
     * @return
     */
    @PostMapping("/customers")
    public RestResponse userInfo(@RequestBody Map params){
        Map<String, Object> map = new HashMap<>();
        //Claims claim = jwtUtils.getClaimByToken(token);
        // userId = claim.getSubject()
        //map.put("staffId",claim.getSubject());

        List<MyCustomersDto> myCustomers = customerService.queryMyCustomers(params);
        map.put("myCustomer",myCustomers);

        return RestResponse.success(map);
    }

    @PostMapping("/addCustomer")
    public RestResponse addCustomer(@RequestBody CustomerParams customerParams){
        Map<String, Object> map = new HashMap<>();
        if(StringUtils.isEmpty(customerParams.getStaffId())){ // 如果不传入员工id，后台获取
            Claims claim = jwtUtils.getClaimByToken(customerParams.getToken());
            customerParams.setStaffId(claim.getSubject()); // 员工id
        }

        CustomerEntity customerEntity = new CustomerEntity();
        BeanUtils.copyProperties(customerParams,customerEntity);
        customerEntity.setCreateTime(DateUtils.stringToDate(customerParams.getCreateTime(),DateUtils.DATE_PATTERN));
        customerService.save(customerEntity);
        map.put("msg","success");
        map.put("code",0);
        map.put("custId",customerEntity.getId());
        return RestResponse.success(map);
    }

    @GetMapping("/customer/detail/{customerId}")
    public RestResponse customerDetail(@PathVariable String customerId){
        Map<String, Object> map = new HashMap<>();
        CustomerEntity customerEntity = customerService.getById(customerId);
        if(customerEntity == null){
            throw new BusinessException("客户不存在");
        }
        CustomerDetailDto customerDetailDto = customerService.constructionDetail(customerEntity);
        map.put("msg","success");
        map.put("code",0);
        map.put("customer",customerDetailDto);
        return RestResponse.success(map);
    }

    /**
     * 显示最近三天客户信息列表-->当前时间前推三天，比如今天是10号，往前三天为8，9，10
     * 参数params:{staffId:1}
     * @param
     * @return
     */
    @PostMapping("/lastdays/customers")
    public RestResponse lastThreeDayCustomers(@RequestBody Map params){
        Map<String, Object> map = new HashMap<>();
        //Claims claim = jwtUtils.getClaimByToken(token);
        // userId = claim.getSubject()
        //map.put("staffId",claim.getSubject());
        params.put("diff",3);
        List<MyCustomersDto> myCustomers = customerService.selectlastThreeDay(params);
        map.put("myCustomer",myCustomers);
        return RestResponse.success(map);
    }


    /**
     * 标记意向
     * 参数params:{staffId:1}
     * @param
     * @return
     */
    @GetMapping("/update/customerStatus/{custId}/{status}")
    public RestResponse updateCoustomerStatus(@PathVariable String status,@PathVariable String custId){
        Map<String, Object> map = new HashMap<>();
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setId(custId);
        customerEntity.setStatus(status);
        boolean flag = customerService.update(customerEntity);
        if(flag){
            CustomerEntity newCustomer = customerService.getById(custId);
            map.put("customer",newCustomer);
        }else{
            throw new BusinessException("标记失败。");
        }
        map.put("msg","success");
        map.put("code",0);
        return RestResponse.success(map);
    }

    /**
     * 客户转移
     * type:0:从公海转入我的；1：从我的转出到公海
     * @param
     * @return
     */
    @GetMapping("/update/customerType/{custId}/{type}")
    public RestResponse updateCoustomerType(@PathVariable String type,@PathVariable String custId,HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setId(custId);
        customerEntity.setType(type);
        if("0".equals(type)){
            //从公海转入我的
            customerEntity.setStaffId((String) request.getAttribute("LOGIN_USER_KEY"));
        }else{
            customerEntity.setStaffId("");
        }
        boolean flag = customerService.updateCustomer(customerEntity);
        if(flag){
            CustomerEntity newCustomer = customerService.getById(custId);
            map.put("customer",newCustomer);
        }else{
            throw new BusinessException("转入失败。");
        }
        map.put("msg","success");
        map.put("code",0);
        return RestResponse.success(map);
    }

    /**
     * 新增跟进记录
     * 参数params:{staffId:1}
     * @param
     * @return
     */
    @PostMapping("/add/record")
    public RestResponse addRecord(@RequestBody RecordParams recordParams){
        Map<String, Object> map = new HashMap<>();

        Date date = DateUtils.stringToDate(recordParams.getCreateTime(), DateUtils.DATE_PATTERN);
        Date nextDate = DateUtils.stringToDate(recordParams.getNextTime(), DateUtils.DATE_PATTERN);
        CustRecordEntity custRecordEntity = new CustRecordEntity();
        custRecordEntity.setCreateTime(date);
        custRecordEntity.setNextTime(nextDate);
        custRecordEntity.setCustId(recordParams.getCustId());
        custRecordEntity.setRecord(recordParams.getRecord());
        custRecordEntity.setType(recordParams.getType());
        boolean save = custRecordService.save(custRecordEntity);
        //TODO 统计客户拜访数,,暂时不在这里计算，统计记录表
        map.put("msg","success");
        map.put("code",0);
        return RestResponse.success(map);
    }

    /**
     * 根据城市查询客户信息
     * 参数params:{staffId:1}
     * @param
     * @return
     */
    @PostMapping("/customers/findByCity")
    public RestResponse findCoustomerByCity(@RequestBody Map params){
        Map<String, Object> map = new HashMap<>();
        List<MyCustomersDto> myCustomers = customerService.queryMyCustomers(params);
        map.put("myCustomer",myCustomers);
        return RestResponse.success(map);
    }

    /**
     * 客户数据统计
     * 参数params:{staffId:1}
     * @param
     * @return
     */
    @PostMapping("/customers/count")
    public RestResponse count(@RequestBody Map params){
        Map<String, Object> map = new HashMap<>();
        CountCoustomerDto countCoustomerDto = new CountCoustomerDto();
        List<MyCustomersDto> myCustomers = customerService.queryMyCustomers(params);

        int todayAdds = 0;
        int monthCoustomers = 0;
        for (int i=0;i<myCustomers.size();i++){
            Date createTime = myCustomers.get(i).getCreateTime();
            String format = DateUtils.format(createTime, DateUtils.DATE_PATTERN);
            String currentDayStr = DateUtils.format(new Date(), DateUtils.DATE_PATTERN);
            if(format.equals(currentDayStr)){
                todayAdds ++;
            }
            String[] split = format.split("-");
            String[] split1 = currentDayStr.split("-");
            String month = split[1];
            String currentMonth = split1[1];
            if(month.equals(currentMonth)){
                monthCoustomers ++;
            }
        }

        List<CustRecordEntity> custRecordEntities = custRecordService.queryAll(map);
        int monthVisCoustomers= 0;
        int todayViss= 0;
        for(CustRecordEntity record : custRecordEntities){
            Date createTime = record.getCreateTime();
            String format = DateUtils.format(createTime, DateUtils.DATE_PATTERN);
            String currentDayStr = DateUtils.format(new Date(), DateUtils.DATE_PATTERN);
            if(format.equals(currentDayStr)){
                todayViss ++;
            }
            String[] split = format.split("-");
            String[] split1 = currentDayStr.split("-");
            String month = split[1];
            String currentMonth = split1[1];
            if(month.equals(currentMonth)){
                monthVisCoustomers ++;
            }
        }

        params.put("diff",3);
        List<MyCustomersDto> follwCoustomers = customerService.selectlastThreeDay(params);
        Integer follwCousts = follwCoustomers.size();
        countCoustomerDto.setMyCoustomers(myCustomers.size());
        countCoustomerDto.setTodayAdds(todayAdds);
        countCoustomerDto.setFollows(follwCousts);
        countCoustomerDto.setMonthCoustomers(monthCoustomers);

        countCoustomerDto.setTodayViss(todayViss + todayAdds);
        countCoustomerDto.setMonthVisCoustomers(monthVisCoustomers);

        List <CustmoerMonthCountEntity> list = customerService.custCount(params);

        map.put("myCustomer",countCoustomerDto);
        map.put("list",list);

        return RestResponse.success(map);
    }

    @GetMapping("/getStaff/{id}")
    public RestResponse staffInfo(@PathVariable String id){
        StaffEntity staffEntity = staffService.getById(id);
        Map<String, Object> map = new HashMap<>();
        StaffDto staffDto = new StaffDto();
        staffDto.setName(staffEntity.getName());
        staffDto.setPhone(staffEntity.getPhone());
        staffDto.setTargetPrice(staffEntity.getTargetPrice());
        map.put("staffInfo",staffDto);
        return RestResponse.success(map);
    }

    @PostMapping("/map/records")
    public RestResponse mapRecord(@RequestBody Map params){
        String lat = (String) params.get("lat");
        String lgt = (String) params.get("lgt");
        String address = (String) params.get("address");
        String staffId = (String) params.get("staffId");
        StaffMapEntity staffMapEntity = new StaffMapEntity();
        staffMapEntity.setAddress(address);
        staffMapEntity.setLat(lat);
        staffMapEntity.setLgt(lgt);
        staffMapEntity.setStaffId(staffId);
        staffMapEntity.setCreateTime(new Date());
        staffMapService.save(staffMapEntity);
        return RestResponse.success();
    }


    /**
     * 修改
     *
     * @param customer customer
     * @return RestResponse
     */
    @RequestMapping("/cust/update")
    public RestResponse update(@RequestBody CustomerEntity customer) {

        customerService.updateCustomerByApp(customer);

        return RestResponse.success();
    }




}
